const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const getBaiduToken = function () {
  return new Promise((resolve, reject) => {
    //自行获取APIKey、SecretKey
    const apiKey = 'KKKshjxC7MLUcnynSYPGUP8P';
    const secKey = '8Xry83T5nT4yowihvYBhyAkwgsckq2L7';
    const tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apiKey}&client_secret=${secKey}`;
    wx.request({
      url: tokenUrl,
      method: 'POST',
      dataType: "json",
      header: {
        'content-type': 'application/json; charset=UTF-8'
      },
      success: function (res) {
        resolve(res);
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试！',
          icon: 'none',
          duration: 2000
        })
        reject(res);
      },
      complete: function (res) {
        resolve(res);
      }
    })
  })
}

//封装识别方法
const searchFace = function (tokenUrl, data) {
  return new Promise((resolve, reject) => {
    const detectUrl = `https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=${tokenUrl}`;
    wx.request({
      url: detectUrl,
      data: data,
      method: 'POST',
      dataType: "json",
      header: {
        'content-type': 'Content-Type:application/json; charset=UTF-8'
      },
      success: function (res) {
        resolve(res);
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试！',
          icon: 'none',
          duration: 2000
        })
        reject(res);
      },
      complete: function (res) {
        resolve(res);
      }
    })
  })
}

module.exports = {
  formatTime: formatTime,
  getBaiduToken: getBaiduToken,
  searchFace: searchFace
}
